<template>
  <div>
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
      <div class="widget am-cf">
        <div class="widget-head am-cf">
          <div class="widget-title am-fl">库存设置</div>
        </div>

        <div class="widget-body  am-fr">
          <div class="am-u-sm-8 am-u-md-8 am-u-lg-2">
            <div class="am-form-group">
              <el-select
                v-model="query.type"
                placeholder="请选择库存类别"
                clearable
              >
                <el-option
                  value="0"
                  label="地推"
                ></el-option>
                <el-option
                  value="1"
                  label="到店物料"
                ></el-option>
                <el-option
                  value="2"
                  label="报读礼品"
                ></el-option>
                <el-option
                  value="3"
                  label="旧带新礼品"
                ></el-option>
                <el-option
                  value="4"
                  label="门店展示"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
            <div class="am-form-group">
              <el-input
                placeholder="物料名称"
                v-model="query.materialName"
              />
            </div>
          </div>

          <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
            <div class="am-form-group">
              <el-select
                placeholder="请选择上下架状态"
                v-model="query.shelvesStatus"
                clearable
              >
                <el-option
                  value="1"
                  label="上架"
                ></el-option>
                <el-option
                  value="0"
                  label="下架"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
            <div class="am-form-group">
              <el-select
                v-model="query.areaTeamId"
                placeholder="选择地区"
                clearable
              >
                <el-option
                  v-for="(item, index) in areaTeams"
                  :key="index"
                  :value="item.value"
                  :label="item.text"
                >
                </el-option>
              </el-select>
            </div>
          </div>

          <div class="am-u-sm-20 am-u-md-20 am-u-lg-8 am-u-end">
            <div class="am-form-group">
              <button
                @click="handleSearch"
                type="button"
                class="am-btn am-btn-default am-btn-success"
              ><span class="am-icon-search"></span>查询
              </button>
              <button
                @click="newCreate"
                type="button"
                class="am-btn am-btn-default am-btn-success"
                v-if="hasPermission('add')"
              >新建
              </button>
            </div>
          </div>
          <div class="am-u-sm-12">
            <el-table
              :data="tableData"
              border
              empty-text="暂无数据"
              stripe
              style="min-width: 100%"
            >
              <el-table-column
                min-width="100"
                prop="areaTeamName"
                label="区域"
              >
              </el-table-column>
              <el-table-column
                min-width="200"
                prop="type"
                label="类别"
              >
                <template scope="scope">
                  <div>{{{'0': '地推','1': '到店物料','2': '报读礼品','3': '旧带新礼品','4': '门店展示'}[scope.row.type]}}</div>
                </template>
              </el-table-column>
              <el-table-column
                min-width="200"
                prop="materialName"
                label="物料名称"
              >
              </el-table-column>
              <el-table-column
                min-width="200"
                prop="unitPrice"
                label="单价（元）"
              >
              </el-table-column>
              <el-table-column
                min-width="100"
                label="用途"
                prop="useMsg"
              >
              </el-table-column>
              <el-table-column
                min-width="150"
                prop="activityName"
                label="关联活动"
              >
                <template scope="scope">
                  <div>{{scope.row.activityName ? scope.row.activityName : ''}}</div>
                </template>
              </el-table-column>
              <el-table-column
                min-width="300"
                prop="periodNames"
                label="关联期数"
              >
              </el-table-column>
              <el-table-column
                min-width="300"
                label="样板图"
              >
                <template scope="scope">
                  <div style="padding:10px 0">
                    <el-popover
                      ref="popover1"
                      placement="right-start"
                      title=""
                      width="320"
                      trigger="hover"
                    >
                      <slot>
                        <div>
                          <img
                            style="width:300px"
                            :src="scope.row.pictureUrl"
                          />
                        </div>
                      </slot>
                    </el-popover>
                    <!-- <img
                      :src="scope.row.pictureUrl"
                      class="tableImage"
                      v-popover:popover1
                    /> -->
                    <el-button v-popover:popover1>查看图片</el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                min-width="300"
                label="上架状态"
              >
                <template scope="scope">
                  <div>{{{'0':'下架', '1':'上架'}[scope.row.shelvesStatus]}}</div>
                </template>
              </el-table-column>
              <el-table-column
                min-width="100"
                label="操作"
                fixed="right"
              >
                <template scope="scope">
                  <div>
                    <el-button
                      @click="goEdit(scope.row)"
                      v-if="hasPermission('edit')"
                    >编辑</el-button>
                    <!-- <el-button
                      @click="viewDetail(scope.row)"
                      v-if="hasPermission('campus_inventory')"
                    >校区库存管理</el-button> -->
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="am-u-lg-12 am-cf">
          <div class="am-fr">
            <pagination
              v-bind:total="total"
              v-bind:pageNo="pageNo"
              v-bind:pageSize="pageSize"
              @paging="loadTableData"
            />
          </div>
        </div>
      </div>
    </div>
    <window
      ref="win"
      :title="mode === 'edit' ? '编辑' : '新建'"
    >
      <div class="settingModal">
        <el-form
          :model="formData"
          ref="settingForm"
          label-width="150px"
          :rules="formRules"
        >
          <el-form-item
            label="区域:"
            prop="areaTeamId"
          >
            <el-select
              v-model="formData.areaTeamId"
              placeholder="选择区域"
              class="itemBox"
            >
              <el-option
                v-for="(item, index) in areaTeams"
                :key="index"
                :value="item.value"
                :label="item.text"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="库存类别:"
            prop="type"
          >
            <el-select
              v-model="formData.type"
              placeholder="请选择库存类别"
              clearable
              class="itemBox"
            >
              <el-option
                value="0"
                label="地推"
              ></el-option>
              <el-option
                value="1"
                label="到店物料"
              ></el-option>
              <el-option
                value="2"
                label="报读礼品"
              ></el-option>
              <el-option
                value="3"
                label="旧带新礼品"
              ></el-option>
              <el-option
                value="4"
                label="门店展示"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="物料名称:"
            prop="materialName"
          >
            <el-input
              v-model="formData.materialName"
              placeholder="填写物料名称"
              class="itemBox"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="单价(元):"
            required
            prop="unitPrice"
          >
            <el-input
              v-model="formData.unitPrice"
              placeholder="填写单价"
              class="itemBox"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用途:"
            prop="useMsg"
          >
            <el-input
              v-model="formData.useMsg"
              placeholder="填写用途"
              class="itemBox"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="样板图:"
            required
            prop="pictureUrl"
          >
            <file-upload
              extensions="jpg,png"
              @uploaded="handleUpload"
              class="itemBox"
            >
              <img
                v-if="formData.pictureUrl"
                class="am-margin-top am-radius"
                :src="formData.pictureUrl"
                style="width:168px;height:168px"
              >
            </file-upload>
          </el-form-item>
          <el-form-item
            label="上架状态:"
            prop="shelvesStatus"
          >
            <el-select
              placeholder="请选择上下架状态"
              v-model="formData.shelvesStatus"
              class="itemBox"
              clearable
            >
              <el-option
                value="1"
                label="上架"
              ></el-option>
              <el-option
                value="0"
                label="下架"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否关联活动:"
            required
          >
            <el-select
              class="itemBox"
              :disabled="!formData.areaTeamId ||  mode === 'edit'"
              v-model="needActivityId"
              @change="needActivityChange($event)"
            >
              <el-option
                value="1"
                label="是"
              ></el-option>
              <el-option
                value="0"
                label="否"
              ></el-option>
            </el-select>
          </el-form-item>
          <div
            v-if="needActivityId == 1"
            class="mdalTable"
          >
            <el-table
              :data="aTableData"
              border
              empty-text="暂无数据"
              stripe
              style="min-width: 100%"
            >
              <el-table-column
                min-width="50"
                label="选择"
              >
                <template scope="scope">
                  <el-radio
                    v-model="tableRadio"
                    :disabled="mode === 'edit'"
                    :label="scope.row.activityId"
                  >&nbsp;</el-radio>
                </template>
              </el-table-column>
              <el-table-column
                min-width="50"
                label="活动标题"
                prop="activityName"
              ></el-table-column>
              <el-table-column
                min-width="50"
                label="活动时间"
              >
                <template scope="scope">
                  <div> {{scope.row.activityStartDate | formatDate }}</div>
                </template>
              </el-table-column>
            </el-table>
            <el-form-item>
              <div class="am-u-lg-12 am-cf">
                <div class="am-fr">
                  <pagination
                    v-bind:total="aTotal"
                    v-bind:pageNo="aPageNo"
                    v-bind:pageSize="aPageSize"
                    @paging="loadActivityData"
                  />
                </div>
              </div>
            </el-form-item>

          </div>
          <el-form-item label="关联期数:">
            <el-select
              v-model="formData.periodIds"
              :disabled="periods.length === 0 ||  mode === 'edit'"
              :multiple="true"
              class="itemBox"
            >
              <el-option
                v-for="(item, index) in periods"
                :key="index"
                :label="item.periodName"
                :value="item.periodId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <div>
            <el-button @click="saveForm">保存</el-button>
          </div>
        </el-form>
      </div>
    </window>
  </div>
</template>
<script>
import io from '../../lib/io'
import Pagination from '../base/Pagination.vue'
import moment from 'moment'
export default {
  data: function() {
    let validateMaxRegNum = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入单价'))
      } else if (!/^[0-9]*$/.test(value)) {
        if (/^[0-9]*[.][0-9]*$/.test(value)) {
          callback()
        } else {
          callback(new Error('请输入数字'))
        }
      } else {
        callback()
      }
    }
    return {
      tableRadio: '',
      total: 0,
      pageSize: 10,
      aPageNo: 1,
      aTotal: 0,
      aPageSize: 10,
      pageNo: 1,
      tableData: [{}],
      aTableData: [],
      mode: '',
      query: {
        type: '',
        materialName: '',
        shelvesStatus: '',
        areaTeamId: ''
      },
      formData: {
        areaTeamId: '',
        type: '',
        materialName: '',
        unitPrice: '',
        useMsg: '',
        pictureUrl: '',
        shelvesStatus: '',
        periodIds: [],
        activityInventorySettingId: ''
      },
      needActivityId: '',
      periods: [],
      formRules: {
        areaTeamId: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        type: [{ required: true, message: '请选择类别', trigger: 'change' }],
        materialName: [
          {
            required: true,
            message: '请填写物料名称',
            trigger: 'blur'
          }
        ],
        unitPrice: [{ validator: validateMaxRegNum, trigger: 'blur' }],
        useMsg: [
          {
            required: true,
            message: '请填写用途',
            trigger: 'blur'
          }
        ],
        pictureUrl: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
        shelvesStatus: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      }
    }
  },
  components: {
    Pagination
  },
  watch: {
    'query.areaTeamId': function(newVal, oldVal) {
      if (!oldVal) {
        this.loadTableData()
      }
    },
    'formData.areaTeamId': function() {
      this.periodIds = []
      this.loadPeriodData()
    }
  },
  computed: {
    areaTeams() {
      let options = (this.$root.config.areaTeams || []).map(item => {
        if (!this.query.areaTeamId) {
          this.query.areaTeamId = item.areaTeamId
        }
        return { value: item.areaTeamId, text: item.name }
      })
      return options
    },
    busTeams: function() {
      let list = this.$root.config.campusList
      return list
    }
  },
  created() {},
  methods: {
    needActivityChange(val) {
      if (val == '1') {
        this.loadActivityData()
      } else {
        this.tableRadio = ''
      }
    },
    saveForm() {
      this.$refs.settingForm.validate(valid => {
        if (valid) {
          if (this.needActivityId == 1) {
            if (!this.tableRadio) {
              this.$alert('请选择活动')
              return
            }
            this.formData.activityId = this.tableRadio
          } else if (this.needActivityId !== '0') {
            this.$alert('请关联活动')
            return
          }
          this.formData.periodIds = this.formData.periodIds.join(',')
          io.postPlayload(
            io.saveOrUpdateActivityInventorySetting,
            this.formData,
            ret => {
              if (ret.success) {
                this.$toast('操作成功')
                this.$refs.win.close()
                this.loadTableData(1)
              } else {
                this.$alert(ret.desc)
              }
            },
            res => {
              this.formData.periodIds = this.formData.periodIds.split(',')
            }
          )
        }
      })
    },
    goEdit(row) {
      this.mode = 'edit'
      this.formData = row
      if (this.formData.activityId) {
        this.tableRadio = this.formData.activityId
        this.needActivityId = '1'
      } else {
        this.needActivityId = '0'
      }
      if (
        this.formData.periodIds &&
        typeof this.formData.periodIds === 'string'
      ) {
        this.formData.periodIds = this.formData.periodIds.split(',')
      }
      this.$refs.win.show({
        width: 600
      })
    },
    viewDetail(row) {
      this.$router.push({
        path: '/main/activity/campusInventory',
        query: { activityInventorySettingId: row.activityInventorySettingId }
      })
    },
    loadPeriodData() {
      io.post(
        io.apiAdminPeriodListForAreaTeam,
        {
          areaTeamId: this.formData.areaTeamId
        },
        ret => {
          if (ret.success) {
            this.periods = ret.data
            this.formData.periodId = ret.data.filter(
              item => item.isCurrent == 1
            )[0]
              ? ret.data.filter(item => item.isCurrent == 1)[0].periodId
              : ''
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    },
    handleUpload(info) {
      if (info.state === 'SUCCESS') {
        this.formData.pictureUrl = info.url
      }
    },
    newCreate() {
      this.mode = 'create'
      this.needActivityId = ''
      this.formData = {
        areaTeamId: '',
        type: '',
        materialName: '',
        unitPrice: '',
        useMsg: '',
        pictureUrl: '',
        shelvesStatus: '',
        periodIds: []
      }
      this.$refs.win.show({
        width: 600
      })
    },
    handleSearch() {
      this.loadTableData(1)
    },
    goExport() {
      io.downloadFile(
        io.exportActivityRegSituation,
        this.formatData(this.query),
        res => {}
      )
    },
    loadTableData(pageNo) {
      this.pageNo = pageNo || this.pageNo || 1
      this.$showLoading()
      io.post(
        io.findActivityInventorySetting,
        Object.assign({}, this.formatData(this.query), {
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }),
        ret => {
          this.$hiddenLoading()
          if (ret.success) {
            this.tableData = ret.data.list
            this.total = ret.data.total
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    },
    loadActivityData(pageNo) {
      this.aPageNo = pageNo || this.aPageNo || 1
      io.post(
        io.findActivityDetailPage,
        {
          pageNo: this.aPageNo,
          pageSize: this.aPageSize,
          shelvesStatus: 1,
          areaTeamId: this.formData.areaTeamId
        },
        ret => {
          // this.$hiddenLoading()
          if (ret.success) {
            this.aTableData = ret.data.list
            this.aTotal = ret.data.total
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    },
    formatData(data) {
      return {
        type: data.type,
        areaTeamId: data.areaTeamId,
        materialName: data.materialName,
        campusId: data.campusId,
        shelvesStatus: data.shelvesStatus
      }
    }
  }
}
</script>
<style lang="less" scoped>
.tableImage {
  width: 80px;
}
.itemBox {
  float: left;
  width: 300px;
}
.mdalTable {
  margin: 10px 30px;
}
.el-form {
  margin: 0;
}
</style>
